﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Services;
using RndMaterialDisposalService.Services.Interface;
using Ganss.Excel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System.Net.Mime;

namespace RndMaterialDisposalService.Controllers
{
    /// <summary>
    /// 资产清退报废电子流
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class CapitalScrapElectronFlowController : ControllerBase
    {
        private ILogger<CapitalScrapElectronFlowController> logger;
        private readonly IConfiguration configuration;
        private readonly ICapitalScrapReportFormService capitalScrapReportFormService;
        private readonly string ProcessFullName = "AssetsManagement\\AssetRetirement";
        private readonly IPortalCommonService portalCommonService;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="_logger"></param>
        /// <param name="_capitalScrapReportFormService"></param>
        /// <param name="_configuration"></param>
        public CapitalScrapElectronFlowController(ILogger<CapitalScrapElectronFlowController> _logger, 
            ICapitalScrapReportFormService _capitalScrapReportFormService, IConfiguration _configuration, IPortalCommonService _IPortalCommonService) 
        {
            logger = _logger;
            capitalScrapReportFormService = _capitalScrapReportFormService;
            configuration = _configuration;
            portalCommonService = _IPortalCommonService;
        }


        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="procInstID">流程实例编号</param>
        /// <returns></returns>
        [HttpGet("GetFormData")]
        public async Task<IActionResult> GetFormData(string? procInstID) 
        {
            var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
            var result = new FormInfoResp();
            if (!string.IsNullOrWhiteSpace(procInstID)) 
            {
                var url = $"{CommonServiceHost}/api/WorkflowData/ApplicationData";
                result = await HttpHelper.GetAsync<FormInfoResp>($"{url}?procInstID={procInstID}");
                result.ViewsStatus = "Approval";
                return Ok(result);
            }

            var formDataModel = new CapitalScrapElectronFlowReq();
            var formDataUrl = $"{CommonServiceHost}/api/WorkflowData/ApplicationNumber";
            var appNumber = await HttpHelper.GetAsync<string>($"{formDataUrl}?workflowCode={ProcessFullName}");
            result.ApplicationNumber = appNumber;
            result.ViewsStatus = "Start";
            result.FormData = JsonConvert.SerializeObject(formDataModel);
            return Ok(result);
        }

        /// <summary>
        /// 保存报表数据
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("SaveReportData")]
        public async Task<IActionResult> SaveReportData(CapitalScrapElectronFlowReq formData)
        {
            string _ProcInstId = formData.formHeader.ProcInstId ?? "0";
            try
            {
                var result2 = await capitalScrapReportFormService.AddCapitalScrapBusinessData(formData);
                logger.LogInformation($"新增报表数据（资产清退报废电子流）,流程实例号：{_ProcInstId},数量：{result2},时间：{DateTime.Now}");
                return Ok(result2);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"新增报表数据（资产清退报废电子流）,流程实例号：{_ProcInstId},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                throw;
            }
        }

        /// <summary>
        /// 资产清退报废电子流报表数据
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("CapitalScrapReport")]
        [PageList]
        [Consumes(MediaTypeNames.Application.Json)]
        [ProducesResponseType(typeof(ScrapReportDataResp), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetCapitalTransferReportFormData(ScrapReportReq inputCondition)
        {
            var list = await capitalScrapReportFormService.CapitalScrapReportData(inputCondition);
            var rep = ApiResponsePageList<ScrapReportDataResp>.CreatePageListByResult(list.Item1, inputCondition.PageNum ?? 1, inputCondition.PageSize ?? 10, list.Item2);
            return Ok(rep);
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="relativePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet("DownloadFile")]
        [PageList]
        public async Task<IActionResult> DownloadFile(string relativePath, string fileName)
        {
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            var fileFullPath = $"{fileDir}\\{relativePath}";
            var stream = await System.IO.File.ReadAllBytesAsync(fileFullPath);
            return File(stream, "application/octet-stream", fileName);
        }

        /// <summary>
        /// 导出报表文件
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("CapitalScrapReportExport")]
        [PageList]
        public async Task<IActionResult> CapitalScrapReportExport(ScrapReportReq inputCondition)
        {
            inputCondition.PageNum = 1;
            inputCondition.PageSize = 65535;
            var list = await capitalScrapReportFormService.CapitalScrapReportData(inputCondition);
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            if (!System.IO.Directory.Exists($"{fileDir}\\Report"))
            {
                Directory.CreateDirectory($"{fileDir}\\Report");
            }
            var filePath = $"Report\\资产清退报废电子流报表{Guid.NewGuid().ToString("N")}.xlsx";
            await new ExcelMapper().SaveAsync($"{fileDir}\\{filePath}", list.Item1);
            return Ok(filePath);
        }

        /// <summary>
        /// 获取待办列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="keyWord"></param>
        /// <param name="sortField"></param>
        /// <param name="SortDir"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetPCTodoList")]
        [PageList]
        public async Task<IActionResult> GetPCTodoList(string userId, string? applicationNumber, string? keyWord, string? sortField = "ArrivalDate", string? SortDir = "desc", int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var result = portalCommonService.GetPCTodoList(userId, "", sortField, SortDir, pageIndex, 100000000);

                result = result.Where(a => a.ModuleDescription == "资产清退报废电子流" && (a.FunctionDescription == "9.财务部资产转移账务处理" || a.FunctionDescription == "12.财务报废")).ToList();
                if (!string.IsNullOrWhiteSpace(applicationNumber)) 
                {
                    result = result.Where(a => a.ApplicationNumber.Contains(applicationNumber)).ToList();
                }
                if (!string.IsNullOrWhiteSpace(keyWord)) 
                {
                    result = result.Where(a => a.FunctionDescription.Contains(keyWord)).ToList();
                }
                var totalCount = result.Count();
                var userResult = ApiResponsePageList<BatchApprovalToDoModel>.CreatePageListByResult(result, pageIndex, pageSize, totalCount);
                return Ok(userResult);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"获取待办列表(批量审批数据),用户ID：{userId},搜索：{keyWord},时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }

    }
}
